/**
 * created by dpf
 * 断面分析
 */
define([
  'dojo/_base/declare',
  'dojo/_base/html',
  'dojo/query',
  'dojo',
  'dojo/aspect',
  'dojo/on',
  'dojo/dom',
  'dojo/dom-style',
  'dojo/_base/Color',
  'dojo/_base/lang',
  'dojo/_base/xhr',
  'dojo/_base/array',
  'dojo/dom-construct',
  'dojo/_base/json',
  'dojo/data/ItemFileWriteStore',
  'dojox/grid/DataGrid',
  './common',
  'esri/toolbars/draw',
  'esri/graphic',
  'esri/layers/GraphicsLayer',
  "esri/layers/ArcGISDynamicMapServiceLayer",
  'esri/symbols/SimpleLineSymbol',
  'esri/symbols/SimpleFillSymbol',
  'esri/symbols/SimpleMarkerSymbol',
  'esri/geometry/Point',
  'esri/geometry/Multipoint',
  'esri/geometry/Polygon',
  'esri/geometry/Extent',
  'esri/SpatialReference',

  "esri/tasks/query", "esri/tasks/QueryTask",

  'dijit/_WidgetsInTemplateMixin',
  'dijit/layout/TabContainer',
  'dijit/layout/ContentPane',
  'dijit/form/Button',
  'dijit/registry',
  'jimu/BaseWidget',
  'jimu/dijit/Message',
  'jimu/dijit/AppStatePopup',
  './LoadingIndicator',
  'libs/echarts/5.22/echarts',
  'libs/proj4js/dist/proj4',
],
  function (declare, html, query, dojo, aspect, on, dom, domStyle, Color, lang, xhr, array, domConstruct, json,
    ItemFileWriteStore, DataGrid, common, Draw, Graphic, GraphicsLayer, ArcGISDynamicMapServiceLayer, SimpleLineSymbol, SimpleFillSymbol,
    SimpleMarkerSymbol, Point, Multipoint, Polygon, Extent,SpatialReference, Query, QueryTask,
    _WidgetsInTemplateMixin, TabContainer,
    ContentPane, Button, registry, BaseWidget, Message, AppStatePopup, LoadingIndicator,echarts, proj4) {
    console.log(echarts)
    console.log(echarts.version)
    var clazz = declare([BaseWidget, _WidgetsInTemplateMixin], {
      width:500,
      baseClass: 'jimu-widget-analysis',
      toolbar: null,
      map: null,
      lyrIncidents: null,
      incident: null,
      resEchart: null,
      names: [],
      nameDataes: [],
      dictionaryTable: [],
      echart: undefined,
      loading: null,
      tableData: {
        identifier: 'id',
        items: []
      },
      loadingNode: null,
      graphicPiont: null,
      incidentPiont: null,
      num: 0,
      GPSPionts: [],
      symPoly: null,
      incidentPoly: [],
      graphicPolyon: null,
      polyGraphic: null,
      button2: null,
      button1: null,
      coordsList: {
        identifier: 'id',
        items: []
      },
      rowData: null,
      containerTab: null,
      appConfig: null,
      config:null,
      projection: [
        {
          wkid: 4326,
          proj4: '+proj=longlat +datum=WGS84 +no_def'
        },
        {
          wkid: 4490,
          proj4: '+proj=longlat +ellps=GRS80 +no_defs'
        },
        {
          wkid: 3857,
          proj4: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs'
        }
      ],
      proj: null,
      url: 'http://118.31.43.251:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer/intersect',
      coordsStore: null,
      option: null,
      // query task and query for parcels
      qtUrl: "",
      queryTask: null,
      query: null,
      qtGeometryType: null,
      postCreate: function () {
        this.inherited(arguments)
      },
      constructor: function ( /*Object*/ options, mapDivId) {
        console.log(options)
        this.appConfig = options.appConfig
        this.config = options.config
      },
      startup: function () {
        // this.map.getExen
        this.inherited(arguments)
        this.map.centerAndZoom([0.05534044758312709, 0.025630269688248296], 12)
        this.containerTab = dom.byId('containerTab')
        var $that = this
        // select echart tab event
        
        this._loadUI()
        this.symPoly = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
          new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25])
        this.graphicPolyon = new GraphicsLayer()
        this.graphicPiont = new GraphicsLayer()

        // srhee

        this.map.on('click', e => {
          console.log(e)
        })
      },
      onClose: function () {
        console.log('duanmian wedgit close...')
        registry.byId("containerTab").destroy();
      },
      // 节点的渲染
      _loadUI: function () {
        // 绑定监听事件
        this.toolbar = new Draw(this.map, {
          tooltipOffset: 20,
          drawTime: 90
        })
        this.toolbar.on('draw-end', lang.hitch(this, this._drawIncident))

        // add srhee
        let htmlselect = '<option value="" geometryType="">请下拉选择!</option>';
        console.log(this.appConfig)
        this.config.layers.forEach((item)=>{
          htmlselect += `<option value="${item.uri}" geometryType="${item.geometryType}">${item.name}</option>`
        })
        document.getElementById("layerToQuery").innerHTML = htmlselect
        console.log($);
        $("#layerToQuery").on('change' , (e)=>{
          console.log(e)
          var obj = document.getElementById('layerToQuery'); // 定位id
          var index = obj.selectedIndex; // 选中索引
          this.qtUrl = obj.options[index].value; // 选中值
          this.qtGeometryType = obj.options[index].getAttribute('geometryType');
        })
      },
      // 点选
      _drawPolyline: function () {
        console.log(this.qtGeometryType)
        if (this.qtUrl === '' || !this.qtGeometryType) {
          alert('请先选择带查询图层!')
        }else{
          this.toolbar.activate(Draw.POLYLINE)
          this.disableWebMapPopup()
        }
      },
      _addPiont(latlng) {
        if (this.incidentPiont !== null) {
          this.incidentPiont = null
        }
        this.GPSPionts.push([latlng.longitude, latlng.latitude])
        var point = new Point(latlng.longitude, latlng.latitude, new SpatialReference({ wkid: this.proj[0].wkid }))
        this.map.centerAt(point)
        this._addPiontToMap()
      },
      _addPiontToMap: function () {
        var mpJson = { 'points': this.GPSPionts, 'spatialReference': ({ ' wkid': this.proj[0].wkid }) }
        var multipoint = new Multipoint(mpJson)
        var cls = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
          new Color([236, 58, 4, 1]), 1)
        var symPoint = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_CIRCLE, 10, cls, new Color([236, 58, 4, 1]))
        this.incidentPiont = new Graphic(multipoint, symPoint)
        this.graphicPiont.add(this.incidentPiont)
        this.map.addLayer(this.graphicPiont)
        this.map.setZoom(17)
        if (this.GPSPionts.length > 2) {
          this._structurePolygon()
        }
      },
      _structurePolygon: function () {
        domStyle.set(this.containerTab, 'display', 'block')
        if (this.graphicPolyon !== null) {
          this._clearPoly()
        }
        var singleRingPolygon = new Polygon({ wkid: this.proj[0].wkid })
        singleRingPolygon.addRing(this.GPSPionts)
        this.polyGraphic = new Graphic(singleRingPolygon, this.symPoly)
        this.graphicPolyon.add(this.polyGraphic)
        this.map.addLayer(this.graphicPolyon)
        this.map.setExtent(this.polyGraphic._extent)
        if (this.graphicPolyon !== null) {
          this._doIntersectAnalysis(this.polyGraphic.geometry)
        }
      },
      _clearEcharts() {
        if (this.echart !== undefined) {
          this.resEchart.remove()
          this.resEchart.innerHTML = ''
          this.echart.dispose()
          this.names = []
          this.nameDataes = []
          this.options = {}
          dojo.destroy('resEchart')
        }
      },
      /**
       * 清除绘面
       * @private
       */
      _clearPoly: function () {
        this.map.graphics.clear()

        if (this.lyrIncidents !== null) {
          this.lyrIncidents.clear()
          this.incident = null
          this.toolbar.deactivate()
        }

        if (this.graphicPolyon !== null) {
          this.graphicPolyon.clear()
          this.polyGraphic = null
        }

        // table clear
        this._clearEcharts()
        // table clear
        this.tableData.items = []
        dom.byId('gridDiv').innerHTML = ''

        this.loading = null
      },
      
      /**
       * 清除事件
       * @private
       */
      _clear: function () {
        this.GPSPionts = []
        this.num = 0
        if (this.graphicPiont !== null) {
          this.graphicPiont.clear()
          this.incidentPiont = null
        }

        // dom.byId('chartsMain').innerHTML = ''
        this._clearPoly()
        // domStyle.set(this.containerTab, 'display', 'none')
      },
      /**
       * draw incidents
       * @param evt
       * @private
       */
      // srhee
      _drawIncident: function (evt) {
        console.log(evt);
        this.lyrIncidents = new GraphicsLayer()
        this.incident = new Graphic(evt.geometry, this.symPoly)
        this.lyrIncidents.add(this.incident)
        try {
          this.map.addLayer(this.lyrIncidents)
          this.map.setExtent(this.incident._extent)
          this._doIntersectAnalysis(this.incident.geometry)
        } catch (e) {
          console.error(e)
        }
        this.toolbar.deactivate()
      },
      disableWebMapPopup: function () {
        if (this.map) {
          this.map.setInfoWindowOnClick(false)
        }
      },
      /**
       * 相交分析
       * @param geom
       * @private
       */
      // srhee
      _doIntersectAnalysis(geom) {
        var node = domConstruct.create('div')

        domStyle.set(node, {
          'min-height': '450px',
          'max-width': '300px'
        })
        this.loading = new LoadingIndicator()

        this.loading.show()
        let pxWidth = this.map.extent.getWidth() / this.map.width;
        let padding = 3 * pxWidth;
        let qGeom = new Extent({
          "xmin": geom.x - padding,
          "ymin": geom.y - padding,
          "xmax": geom.x + padding,
          "ymax": geom.y + padding,
          "spatialReference": geom.spatialReference
        });
        this.queryTask = new QueryTask(this.qtUrl),
        this.query = new Query();
        this.query.returnGeometry = true;
        this.query.outFields = ["*"];

        this.query.geometry = geom;

        this.queryTask.execute(this.query).then(lang.hitch(this, this.handleQueryResults))
      },

      handleQueryResults(results) {
        console.log("queries finished: ", results);
        var features = results.features;
        // this.map.graphics.clear();
        // add the results to the map
        let symbol;
        switch ( this.qtGeometryType){
          case 'polyline':
            symbol = new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_DASH,
              new Color([0,0,255]),
              3
            );
            break;
          default:
            break
        }
        let attrHtml=''
        array.forEach(features, (feat) =>{
          feat.setSymbol(symbol);
          this.map.graphics.add(feat);

          Object.keys(feat.attributes).forEach(function(key) {
            attrHtml += `<div><b>${key}:</b><span>${feat.attributes[key]}</span></div>`
          })
          attrHtml += '<hr />'
        });
        
        $("#gridDiv").html(attrHtml);
        this.loading.hide();

        // 随机生成图表(示例,模拟数据)
        this._initChart()
      },

      _initChart(){
        let option = this._getOption();
        var chartDom = document.getElementById('chartsMain');
        var myChart = echarts.init(chartDom);
        option && myChart.setOption(option);
      },
      _getOption(){
        return option = {
          title: {
            text: ''
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: ['输水', '排水', '燃气', '电力']
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: ['', '', '', '', '', '', '','','','']
            }
          ],
          yAxis: [
            {
              type: 'value',
              axisLabel: {
                formatter: '{value}m'
              }
            }
          ],
          series: [
            {
              name: '输水',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this._generateArr(10,-10,-16)
            },
            {
              name: '燃气',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this._generateArr(10,-13,-18)
            },
            {
              name: '排水',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this._generateArr(10,-23,-28)
            },
            {
              name: '电力',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this._generateArr(10,-32,-39)
            }
          ]
        };        
      },

      _generateArr(n,min,max){
        var arr = new Array(n);
        for(var i=0;i<arr.length;i++){
          arr[i] = Math.round(Math.random()*(max - min) + min + 1);;
        }
        return arr;
      }

    })

    return clazz
  })
